package com.zzy.rpctest;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import com.zzy.rpc.RPC;

public class UploadFileImpl implements UploadFile{

	@Override
	public boolean copyLocalFile(String srcPath, String destPath) {
		UploadFile uploadFile = RPC.getProxy(UploadFile.class, "192.168.10.130", 9111);
		byte[] buffer = uploadFile.getByte(srcPath);
		
		File destFile = new File(destPath);
		if(!destFile.exists()){
			destFile.mkdir();
		}

		String srcPathFileName = srcPath.substring(srcPath.lastIndexOf("\\")+1, srcPath.length());
		OutputStream out = null;
		try {
			out = new FileOutputStream(destPath + srcPathFileName);
			out.write(buffer);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		return true;
	}
	@Override
	public byte[] getByte(String path) {
		BufferedInputStream in = null;
		ByteArrayOutputStream out = null;
		byte[] content = null;
		try {
			in = new BufferedInputStream(new FileInputStream(path));
			out = new ByteArrayOutputStream(1024);
		        
		        System.out.println("Available bytes:" + in.available());         
		        
		        byte[] temp = new byte[1024];         
		        int size = 0;         
		        while (in.available() > 0 && (size = in.read(temp)) != -1) {         
		            out.write(temp, 0, size);         
		        }         
		        content = out.toByteArray();         
		        System.out.println("Readed bytes count:" + content.length);         
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				out.close();
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return content;
//		byte[] buffer = null;
//		File file = new File(path);
//		FileInputStream in = null;
//		int position = 0;
//		byte data;
//		try {
//			in = new FileInputStream(file);
//			buffer = new byte[in.available()];
//			while(in.available() > 0 && (data = (byte) in.read()) != -1) {
//				buffer[position ++] = data;
//			}
//		} catch (FileNotFoundException e1) {
//			e1.printStackTrace();
//		} catch (IOException e) {
//			e.printStackTrace();
//		}finally {
//			try {
//				in.close();
//			} catch (IOException e) {
//				e.printStackTrace();
//			}
//		}
//		return buffer;
		
	}
	@Override
	public boolean mkdir(String path) {
		File file = new File(path);
		if(!file.exists()) {
			return file.mkdirs();
		}
		return false;
	}

}
